package com.fingard.dsp.interact.custom.trustlife;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.fingard.FGBiz;
import com.fingard.common.utils.json.JSONUtils;
import com.fingard.constant.Format;
import com.fingard.crypto.DigestHelper;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.interact.DownloadFileReq;
import com.fingard.dsp.interact.DownloadFileResp;
import com.fingard.dsp.interact.FileServerInvokerBase;
import com.fingard.dsp.interact.GenerateUrlReq;
import com.fingard.dsp.interact.GenerateUrlResp;
import com.fingard.dsp.interact.IFileServerInvoker;
import com.fingard.dsp.interact.UploadFileReq;
import com.fingard.dsp.interact.UploadFileResp;
import com.fingard.generalobj.ExecResponse;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;

/**访问文件服务器调用类*/
public class FileServerInvoker extends FileServerInvokerBase implements IFileServerInvoker {
	
	private String logCode = "trustlife"+File.separator+"FileServerInvoker";

	public void setLogCode(String pLogCode) {
		logCode = pLogCode;
	}
	
	public UploadFileResp uploadFile(UploadFileReq req){
		
		UploadFileResp resp = new UploadFileResp();
		resp.isCompleted = false;
		OSSClient ossClient = null;
		InputStream input = null;
		try {
			initFsSet(req.upFileName);
			if(StringHelper.isNullOrEmpty(fsSet.ossSet.endpoint)){
				FGBiz.logTrace.error(logCode, "ossSet.endpoint为空");
			}
			if(StringHelper.isNullOrEmpty(fsSet.ossSet.accessKeyId)){
				FGBiz.logTrace.error(logCode, "ossSet.accessKeyId为空");
			}
			if(StringHelper.isNullOrEmpty(fsSet.ossSet.accessKeySecret)){
				FGBiz.logTrace.error(logCode, "ossSet.accessKeySecret为空");
			}
			if(StringHelper.isNullOrEmpty(fsSet.ossSet.securityToken)){
				FGBiz.logTrace.error(logCode, "ossSet.securityToken为空");
			}
			if(StringHelper.isNullOrEmpty(fsSet.ossSet.bucket)){
				FGBiz.logTrace.error(logCode, "ossSet.bucket为空");
			}
			if(StringHelper.isNullOrEmpty(fsSet.ossSet.objectKey)){
				FGBiz.logTrace.error(logCode, "ossSet.objectKey为空");
			}
			ossClient = new OSSClient(fsSet.ossSet.endpoint, fsSet.ossSet.accessKeyId, fsSet.ossSet.accessKeySecret, fsSet.ossSet.securityToken);
			
			FGBiz.logTrace.debug(logCode, "上传objectKey为"+fsSet.ossSet.objectKey);
			File ufile = new File(req.upFileLocalPath);
			input = new FileInputStream(ufile);
			
			PutObjectResult putResult = ossClient.putObject(fsSet.ossSet.bucket, fsSet.ossSet.objectKey, input);
			input.close();
			input = null;
			
			//PutObjectResult putResult = ossClient.putObject(fsSet.ossSet.bucket, upfilename, new File(req.upFileLocalPath));
			resp.sbMsg.append("getETag:" + putResult.getETag()+"\r\n");
			resp.sbMsg.append("getResponse:" + putResult.getResponse()+"\r\n");
			resp.sbMsg.append("getRequestId:" + putResult.getRequestId()+"\r\n");
			FGBiz.logTrace.debug(logCode, "上传成功");
	        //ossClient.setObjectAcl(fsSet.ossSet.bucket, fsSet.ossSet.objectKey, CannedAccessControlList.PublicRead);
	        resp.isCompleted = true;
	        resp.rtnFileId = fsSet.ossSet.objectKey;
	        
	        FGBiz.logTrace.debug(logCode, resp.sbMsg.toString());
			

		}catch (OSSException oe) {
			FGBiz.logTrace.exception(logCode, oe);
			resp.sbMsg.append("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
			resp.sbMsg.append("Error Message: " + oe.getErrorCode());
			resp.sbMsg.append("Error Code:       " + oe.getErrorCode());
			resp.sbMsg.append("Request ID:      " + oe.getRequestId());
			resp.sbMsg.append("Host ID:           " + oe.getHostId());
			resp.sbMsg.append("getStackTrace: " + LogHelper.getStackTrace(oe));
        } catch (ClientException ce) {
        	FGBiz.logTrace.exception(logCode, ce);
        	resp.sbMsg.append("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
        	resp.sbMsg.append("getStackTrace: " + LogHelper.getStackTrace(ce));
        }catch(Throwable e){
        	resp.sbMsg.append(LogHelper.getStackTrace(e));
			FGBiz.logTrace.exception(logCode, e);
		}finally {
			if(input!=null){
				try {
					input.close();
				} catch (IOException e) {
					FGBiz.logTrace.exception(logCode, e);
				}
			}
			if(ossClient != null){
				try{
					ossClient.shutdown();
				}catch(Throwable ex){
					FGBiz.logTrace.exception(logCode, ex);
				}
			}
		}

		return resp;
	}
	
	private void initFsSet(String pFileName) throws Exception{
		if(StringHelper.isNullOrEmpty(fsSet.customServerUrl)){
			throw new Exception("未配置客制化服务地址customServerUrl");
		}
		//if(StringHelper.isNullOrEmpty(fsSet.ossSet.endpoint)){//从ATS获取oss参数
			FGBiz.logTrace.info(logCode, "请求参数地址："+fsSet.customServerUrl);
			String charset = "utf-8";
			fsSet.ossSet.ossType = "aliyun";
			WebRequest webreq = new WebRequest(fsSet.customServerUrl);
			String transTime = Format.DateTimeFormat.format(new Date());
			String digStr = "getOssParam"+transTime+pFileName+"ueeo(&8292meyy72$%2099@11djde";
			byte[] bytesOri = digStr.getBytes(charset);
			String sha1 = DigestHelper.cryptoSHA1RetHexStr(bytesOri);
			String reqStr1 = "{\"transType\":\"getOssParam\",\"transTime\":\""+transTime+"\",\"fileName\":\""+pFileName+"\",\"digest\":\""+sha1+"\"}";
			FGBiz.logTrace.info(logCode, "请求json：\r\n"+reqStr1);
			String reqStr2 = "reqstr="+URLEncoder.encode(reqStr1, charset);
			FGBiz.logTrace.info(logCode, "post：\r\n"+reqStr2);
			byte[] upBytes = reqStr2.getBytes(charset);
			
			String[] retVals = webreq.upload(upBytes, charset);
			//FGBiz.limitMsg.add("trustlife.getOssParam", retVals[0]+"-"+retVals[1]);
			if(retVals[0].length()==0){
				FGBiz.logTrace.info(logCode, "响应json：\r\n"+retVals[1]);
				HashMap<String, String> hashParam = JSONUtils.json2Map(retVals[1]);
				if(hashParam.containsKey("respCode") && "0".equals(hashParam.get("respCode"))){
					/*"bucket":"za-electronicreceipt",
"endpoint":"http://oss-cn-hzjbp-b-internal.aliyuncs.com",
"accessKeyId":"LTAI2b7mSW4zuneN",
"accessKeySecret":"bjXPxBtI8JIIZr2ulQzemMCFm2vzxJ"}
*/
					if(hashParam.containsKey("bucket")){
						fsSet.ossSet.bucket = hashParam.get("bucket");
					}
					if(hashParam.containsKey("endpoint")){
						fsSet.ossSet.endpoint = hashParam.get("endpoint");
					}
					if(hashParam.containsKey("accessKeyId")){
						fsSet.ossSet.accessKeyId = hashParam.get("accessKeyId");
					}
					if(hashParam.containsKey("accessKeySecret")){
						fsSet.ossSet.accessKeySecret = hashParam.get("accessKeySecret");
					}
					if(hashParam.containsKey("securityToken")){
						fsSet.ossSet.securityToken = hashParam.get("securityToken");
					}
					if(hashParam.containsKey("objectKey")){
						fsSet.ossSet.objectKey = hashParam.get("objectKey");
					}
				}else{
					String respInfo = "";
					if(hashParam.containsKey("respInfo")){
						respInfo = hashParam.get("respInfo");
					}
					throw new Exception("从服务地址取参数失败："+respInfo);
				}
			}else{
				throw new Exception("连接客制化服务地址customServerUrl："+fsSet.customServerUrl+"失败："+retVals[0]+"-"+retVals[1]);
			}
		//}
	}
	
	public DownloadFileResp downloadFile(DownloadFileReq req){
		DownloadFileResp resp = new DownloadFileResp();
		try{
			initFsSet(req.fileId);
			com.fingard.dsp.interact.oss.aliyun.FileServerInvoker aliFs = new com.fingard.dsp.interact.oss.aliyun.FileServerInvoker();
			resp = aliFs.downloadFile(req);
		}catch(Exception e){
			resp.sbMsg.append(e);
			FGBiz.logTrace.exception(logCode, e);
		}finally{

		}
		return resp;
	}
	
	public GenerateUrlResp generateUrl(GenerateUrlReq req) {
		GenerateUrlResp resp = new GenerateUrlResp();
		resp.isCompleted = false;
		resp.sbMsg.append("未实现该接口");
		return resp;
	}

	public ExecResponse pushData(ArrayList<ReceiptData> pDataList) {
		ExecResponse resp = new ExecResponse();
		resp.logMsg = "不需实现";
		return resp;
	}
}
